package com.wit.health.decorator;

import android.content.Context;
import android.util.AttributeSet;
import android.widget.VideoView;


/**
* 自定义VideoView,保证视频比例不失真
*
* @Author liaozhaoping
* @Date 2024-09-24 16:32
*/
public class AspectRatioVideoView extends VideoView {

    private float aspectRatio = 1.77f; // 默认宽高比

    public AspectRatioVideoView(Context context) {
        super(context);
    }

    public AspectRatioVideoView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public AspectRatioVideoView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    public void setAspectRatio(float aspectRatio) {
        this.aspectRatio = aspectRatio;
        requestLayout();
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        int originalWidth = MeasureSpec.getSize(widthMeasureSpec);
        int originalHeight = MeasureSpec.getSize(heightMeasureSpec);

        int calculatedHeight = (int) (originalWidth / aspectRatio);

        if (calculatedHeight > originalHeight) {
            int calculatedWidth = (int) (originalHeight * aspectRatio);
            setMeasuredDimension(calculatedWidth, originalHeight);
        } else {
            setMeasuredDimension(originalWidth, calculatedHeight);
        }
    }
}
